import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:netease_music/controllers/route_observer_with_player.dart';
import 'package:netease_music/player/controller/audio_player_controller.dart';
import 'package:netease_music/player/controller/bottom_player_overlay_controller.dart';
import 'package:netease_music/router/index.dart';
import 'package:netease_music/theme/theme_controller.dart';
import 'package:netease_music/theme/themes.dart';
import 'package:netease_music/utils/dio_client.dart';

void main() async {
  // 确保 Widget 绑定初始化
  WidgetsFlutterBinding.ensureInitialized();
  // 初始化dio
  await DioUtil().init();
  // 初始化getStorage
  await GetStorage.init();
  // 注入主题控制器
  Get.put(ThemeController());
  // 注入 overlay 底部播放器控制器
  Get.put(BottomPlayerOverlayController());
  // 注入音乐播放控制器
  Get.put(AudioPlayerController());
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    // gex框架入口
    return GetBuilder<ThemeController>(
      init: Get.find<ThemeController>(),
      builder: (themeController) {
        final themeMode = themeController.themeMode;
        return GetMaterialApp(
          title: 'netease-music',
          debugShowCheckedModeBanner: false,
          theme: lightTheme,
          darkTheme: darkTheme,
          themeMode: themeMode,
          initialRoute: '/home', // 初始页面
          getPages: AppPages.routes, // 路由配置
          builder: (context, child) {
            return OverlayWrapper(child: child!);
          },
          navigatorObservers: [RouteObserverWithPlayer()], // 注册自定义的导航观察器
        );
      },
    );
  }
}

// Overlay 包装组件 实现底部音乐导航栏的全局展示
class OverlayWrapper extends StatelessWidget {
  final Widget child;

  const OverlayWrapper({super.key, required this.child});

  @override
  Widget build(BuildContext context) {
    final overlayController = Get.find<BottomPlayerOverlayController>();
    // 添加帧回调，确保 Overlay 初始化
    WidgetsBinding.instance.addPostFrameCallback(
      (_) {
        overlayController.initOverlay(context);
      },
    );
    return child;
  }
}
